package com.handinfo.engine.resource;

import javax.microedition.lcdui.*;

import com.handinfo.util.Tools;

import java.io.*;

/**
 * @author Xia Mingwei
 * @version 1.0
 */
public class SerializeableImage extends Serializeable
{
	public Image m_image;

	public static final int MemThreshold = ((2 << 20) + (1 << 19));// 内存暂定阀值为2.5M

	public static int MemoryValue = 0;

	public SerializeableImage()
	{

	}

	/**
	 * 判断图片内存是否超出
	 * */
	public static boolean isFreeMemory()
	{
		return (MemoryValue >= MemThreshold);
	}

	private void addMemory(Image img)
	{
		if (img == null) {
			return;
		}
		int width = img.getWidth();
		int height = img.getHeight();
		MemoryValue += width * height * 2;
		Tools.debugPrintln("内存增加 当前值为：" + MemoryValue);
	}

	private void delMemory(Image img)
	{
		if (img == null) {
			return;
		}
		int width = img.getWidth();
		int height = img.getHeight();
		MemoryValue -= width * height * 2;
		if (MemoryValue < 0) {
			MemoryValue = 0;
		}
		Tools.debugPrintln("内存减少 当前值为：" + MemoryValue);
	}

	public void read(Resource res, DataInputStream dis) throws IOException
	{
		// readHeader(res, dis);
		// byte[] data = new byte[dis.available()];
		// dis.read(data);
		m_image = Tools.createBinImage(dis);
		if (m_image != null) {
			addMemory(m_image);
			checkLoadFinished();
		}
		else {
//			m_image = Tools.createImage(res.)
			throw new IOException();
		}
	}
	
	public void read(Resource res, byte[] data) throws IOException
	{
		// readHeader(res, dis);
		// byte[] data = new byte[dis.available()];
		// dis.read(data);
		m_image = Tools.createByteImage(data);
		if (m_image != null) {
			addMemory(m_image);
			checkLoadFinished();
		}
		else {
//			m_image = Tools.createImage(res.)
			throw new IOException();
		}
	}
	
	

//	@Override
//	public void read(Resource res, ResHead head) throws IOException {
//		m_image = Tools.createBinImage(head.m_url);
//		if (m_image != null) {
//			addMemory(m_image);
//			checkLoadFinished();
//		}
//		else {
////			m_image = Tools.createImage(res.)
//			throw new IOException();
//		}
//	}

	public synchronized void updateCompose(byte type, String url,
			Serializeable obj)
	{

	}

	public boolean m_loadFinished;

	public void checkLoadFinished()
	{
		m_loadFinished = (m_image == null);
	}

	public void dispose()
	{
		disposeHeader();
		delMemory(m_image);
		m_image = null;
	}

	public void updateComponent(ResHead head, Serializeable compose)
	{

	}

//	@Override
//	public void read(Resource res, DataInputStream dis) throws IOException {
//		// TODO Auto-generated method stub
//		
//	}

}
